import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import AppLogin from '@/pages/AppLogin/index.vue'
import AppLayout from '@/pages/AppLayout/index.vue'
import AppNotFound from '@/pages/AppNotFound/index.vue'
import store from '@/store/auth.js'
import { ElMessage } from 'element-plus'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', name: 'login', component: AppLogin, meta: { isPublic: true } },
    {
      path: '/',
      name: 'main',
      component: AppLayout,
      children: routes
    },
    {
      path: '/not-found',
      name: 'not-found',
      meta: { isPublic: true },
      component: AppNotFound,
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: {
        name: 'not-found'
      }
    },
  ]
})

// 登录鉴权
router.beforeEach((to, from, next) => {
  // 如果需要登录,他没登录,那就请登录
  // auth/isLoginined' 加了命名空间所以需要写auth
  if (!to.meta.isPublic && store.getters['auth/isLoginined']) {
    ElMessage.error('请先登录')
    next({ name: 'login' })
  }
  next()
})

export default router
